/**
 * Copyright 2011, Under-Ground Studio.
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.edu.zju.vlis.aus.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.view.View;
import android.view.View.OnClickListener;
import cn.edu.zju.vlis.aus.MainActivity;
import cn.edu.zju.vlis.aus.R;
import cn.edu.zju.vlis.aus.db.UsageRecordDAO;
import cn.edu.zju.vlis.aus.pref.StatisticsTimeRangePreference;
import cn.edu.zju.vlis.aus.service.LogcatAnalyzeService;
import cn.edu.zju.vlis.aus.util.PreferenceHelper;

public class SettingActivity extends PreferenceActivity implements
		OnPreferenceClickListener, OnClickListener {
	private static final int DIALOG_ID_CONFIRM = 1;
	private static final int DIALOG_ID_PROGRESS = 2;

	private String KEY_STATISTICS_APP_LIST;
	private String KEY_STATISTICS_TIME_RANGE;
	private String KEY_LAUNCH_CONFIRM;
	private String KEY_SERVICE_RUNNING;
	private final static int REQUEST_CODE_SELECT_APP = 1;

	private Preference statisticsAppPreference;
	private CheckBoxPreference launchConfirmPreference;
	private CheckBoxPreference serviceRunningPreference;
	private StatisticsTimeRangePreference timeRangePreference;

	private UsageRecordDAO dao;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		dao = new UsageRecordDAO(this);
		addPreferencesFromResource(R.xml.preferences);

		KEY_STATISTICS_APP_LIST = getResources().getString(
				R.string.preference_key_statistics_app_list);
		KEY_LAUNCH_CONFIRM = PreferenceHelper.KEY_LAUNCH_CONFIRM;
		KEY_SERVICE_RUNNING = PreferenceHelper.KEY_SERVICE_RUNNING;
		KEY_STATISTICS_TIME_RANGE = getResources().getString(
				R.string.preference_key_statitics_time_range);

		statisticsAppPreference = getPreferenceScreen().findPreference(
				KEY_STATISTICS_APP_LIST);
		launchConfirmPreference = (CheckBoxPreference) getPreferenceScreen()
				.findPreference(KEY_LAUNCH_CONFIRM);
		serviceRunningPreference = (CheckBoxPreference) getPreferenceScreen()
				.findPreference(KEY_SERVICE_RUNNING);
		timeRangePreference = (StatisticsTimeRangePreference) getPreferenceScreen()
				.findPreference(KEY_STATISTICS_TIME_RANGE);

		// init the service running
		serviceRunningPreference
				.setChecked(LogcatAnalyzeService.instanceCount == 1);
		serviceRunningPreference.setOnPreferenceClickListener(this);

		statisticsAppPreference.setOnPreferenceClickListener(this);
	}

	@Override
	protected void onDestroy() {
		dao.close();
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_clear_data:
			showDialog(DIALOG_ID_CONFIRM);
			break;
		}
	}

	@Override
	public boolean onPreferenceClick(Preference preference) {
		if (preference == statisticsAppPreference) {
			Intent intent = new Intent(this, SettingAppFilterActivity.class);
			startActivityForResult(intent, REQUEST_CODE_SELECT_APP);
			return true;
		} else if (preference == serviceRunningPreference) {
			MainActivity mainActivity = (MainActivity) getParent();
			if (serviceRunningPreference.isChecked()) {
				mainActivity.startLogcatService();
			} else {
				mainActivity.stopLogcatService();
			}
			return true;
		} else {
			return false;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_CODE_SELECT_APP && resultCode == RESULT_OK) {
			MainActivity parent = (MainActivity) getParent();
			if (parent != null) {
				parent.refreshForAppFilter();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	// called by the UsedRankActivity when the LaunchConfirm was modified there.
	public void updateLaunchConfirm() {
		boolean launchConfirm = PreferenceHelper.getLaunchConfirm(this);
		launchConfirmPreference.setChecked(launchConfirm);
	}

	// refresh the statistics time range
	public void refresh() {
		timeRangePreference.notifyChanged();
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_ID_PROGRESS:
			ProgressDialog dialog = new ProgressDialog(SettingActivity.this);
			String msg = SettingActivity.this.getResources().getString(
					R.string.reset_database_progress_msg);
			dialog.setMessage(msg);
			dialog.setIndeterminate(true);
			dialog.setCancelable(false);
			return dialog;
		case DIALOG_ID_CONFIRM:
			return new AlertDialog.Builder(SettingActivity.this)
					.setTitle(R.string.reset_database_confirm_title)
					.setIcon(android.R.drawable.ic_dialog_alert)
					.setMessage(R.string.reset_database_confirm_msg)
					.setPositiveButton(android.R.string.ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									new RestDatabaseTask().execute();
								}
							})
					.setNegativeButton(android.R.string.cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

								}
							}).create();
		}
		return super.onCreateDialog(id);
	}

	private class RestDatabaseTask extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			showDialog(DIALOG_ID_PROGRESS);
		}

		@Override
		protected Void doInBackground(Void... params) {
			dao.createAndInitTable();
			PreferenceHelper.setStatisitcStartTime(SettingActivity.this,
					System.currentTimeMillis());
			PreferenceHelper.setLastStatisitcTime(SettingActivity.this,
					System.currentTimeMillis());
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			dismissDialog(DIALOG_ID_PROGRESS);
			MainActivity parent = (MainActivity) getParent();
			if (parent != null) {
				parent.scanAndRefreshData();
			}
		}

	}

}
